<template>
  <div class="form-container">
    <h2>登录</h2>
    <form @submit.prevent="handleLogin" class="form-group">
      <div class="form-group">
        <label>用户名</label>
        <input v-model="loginForm.username" type="text" required />
      </div>
      <div class="form-group">
        <label>密码</label>
        <input v-model="loginForm.pwd" type="password" required />
      </div>
      <div v-if="error" class="error">{{ error }}</div>
      <button type="submit">登录</button>
    </form>
    <p class="text-center mt-4">
      没有账号？<router-link to="/register" class="link">去注册</router-link>
    </p >
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import { useUserStore } from '../stores/userStore';

interface LoginForm {
  username: string;
  pwd: string;
}
const apiBase = import.meta.env.VITE_API_BASE_URL;
// 预填充账号和密码
const loginForm = ref<LoginForm>({ username: 'fanyu', pwd: '23007617' });
const error = ref<string>('');
const router = useRouter();
const userStore = useUserStore();

const handleLogin = async () => {
  error.value = ''; // 清空错误消息
  try {
    const response = await axios.post(`${apiBase}/demo/login`, loginForm.value, {
      timeout: 5000,
      headers: {
        // 可选：添加自定义头部
      },
    });
    // 验证 API 返回的 errno
    if (response.status === 200 && response.data.errno === 0) {
      const { data } = response.data;
      const { username, id: userId } = data;
      userStore.login(username, userId);
      router.push({ path: '/success' });
    } else {
      error.value = response.data.message || '登录失败，请检查用户名或密码';
    }
  } catch (err: any) {
    error.value = err.response?.data?.message || '网络错误，请稍后重试';
  }
};
</script>

<style scoped>
.text-center {
  text-align: center;
}
.mt-4 {
  margin-top: 1rem;
}
.error {
  color: red; /* 已修正：确保冒号存在 */
  margin: 0.5rem 0;
}
</style>